package com.example.home.model.service

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.example.home.intent.VideoIntent
import com.example.home.model.api.VideoApi
import com.example.home.state.VideoState
import com.example.mvicore.model.BaseModel
import com.example.net.RetrofitFactory
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.lang.RuntimeException

internal class VideoModel(lifecycleOwner: LifecycleOwner) : BaseModel<VideoIntent, VideoState>(lifecycleOwner) {

    override fun generateInitState(): VideoState {
        return VideoState.VideoInit
    }

    override fun handleIntent() {
        viewModelScope.launch {
            events.receiveAsFlow().collect {
                when(it){
                    is VideoIntent.GetRecommendVideo-> doRecommendVideo(it)
                }
            }
        }
    }

    private suspend fun doRecommendVideo(it:VideoIntent.GetRecommendVideo){
        val videos = RetrofitFactory.create<VideoApi>(VideoApi::class.java)
            .getRecommendVideo(it.page,it.pageSize)
        if (videos.code == 200){
            _status.value = VideoState.VideoSuceess(videos.data)
        }else{
            _status.value = VideoState.VideoFailed(RuntimeException("获取推荐短视频出错"))
        }
    }

}